package com.ragdollcat.thirdaicodegenerate.service.impl;

import cn.hutool.core.util.ZipUtil;
import com.ragdollcat.thirdaicodegenerate.exception.ErrorCode;
import com.ragdollcat.thirdaicodegenerate.exception.ThrowUtils;
import com.ragdollcat.thirdaicodegenerate.service.DownloadAppService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Set;

/**
 * 文件下载
 */
@Service
@Slf4j
public class DownloadAppServiceImpl implements DownloadAppService {

    /**
     * 需要过滤的文件和目录名称
     */
    private static final Set<String> IGNORED_NAMES = Set.of(
            "node_modules",
            ".git",
            "dist",
            "build",
            ".DS_Store",
            ".env",
            "target",
            ".mvn",
            ".idea",
            ".vscode"
    );

    /**
     * 需要过滤的文件扩展名
     */
    private static final Set<String> IGNORED_EXTENSIONS = Set.of(
            ".log",
            ".tmp",
            ".cache"
    );


    /**
     * 下载文件成为压缩包
     *
     * @param fileSavePath
     * @param fileName
     * @param response
     */
    @Override
    public void downloadApp(String fileSavePath, String fileName, HttpServletResponse response) {
        File saveFile = new File(fileSavePath);
        ThrowUtils.throwIf(!saveFile.exists() || !saveFile.isDirectory(), ErrorCode.OPERATION_ERROR, "下载目录不存在，请检查");

        // 设置 HTTP 响应头
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/zip");
        response.addHeader("Content-Disposition",
                String.format("attachment; filename=\"%s.zip\"", fileName));


        //进行文件过滤
        FileFilter fileFilter = file -> isPathAllowed(saveFile.toPath(), file.toPath());

        //使用hutool工具类进行压缩
        try {
            ZipUtil.zip(response.getOutputStream(), StandardCharsets.UTF_8, false, fileFilter, saveFile);
        } catch (IOException e) {
            log.error("zip文件生成错误！", e);
            ThrowUtils.throwIf(true, ErrorCode.SYSTEM_ERROR);
        }

    }


    /**
     * @param savePath D:\Idea_workspace\2025\third-ai-code-generate\tmp\code\vue_project_337058888993742848_1
     * @param fullPath D:\Idea_workspace\2025\third-ai-code-generate\tmp\code\vue_project_337058888993742848_1\index.html
     * @return
     */
    private boolean isPathAllowed(Path savePath, Path fullPath) {
        //index.html
        Path relativize = savePath.relativize(fullPath);
        for (Path path : relativize) {
            if (IGNORED_NAMES.contains(path.getFileName().toString())) {
                return false;
            }
            if (IGNORED_EXTENSIONS.stream().anyMatch(ext -> path.getFileName().toString().endsWith(ext))) {
                return false;
            }
        }
        return true;
    }
}


